import time

from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

# 定义一个函数，来获取不同浏览器的驱动
def getDriver(driverStr):
    if driverStr=="safari":
        driver = webdriver.Safari()
    elif driverStr=="chrome":
        driver = webdriver.Chrome()
    elif driverStr=="firefox":
        driver = webdriver.Firefox()
    else:
        driver = webdriver.Edge()

    return driver



# 定义一个类，封装了不同的操作：关闭浏览器，定位元素 选择下拉框...
class BasePage:
    def __init__(self,driver:webdriver):
        self.driver = driver

    # 打开某个网页
    def open(self,url):
        self.driver.get(url)
        # 窗口最大化
        self.driver.maximize_window()
        # 隐式等待
        self.driver.implicitly_wait(5)

    # 退出浏览器
    def quit(self):
        self.driver.quit()

    # 关闭当前网页
    def close(self):
        self.driver.close()

    # 定位元素
    '''
    target的字符串格式：
    id=值
    class name = 值
    xpath = 值
    link text=值 
    '''
    def locate_element(self,target):
        try:
            # 处理target字符串
            list1 = target.split("=")
            locator = (list1[0].strip(" "),list1[1].strip(" "))
            # 显式等待
            element = WebDriverWait(self.driver, 5, 0.5).until(expected_conditions.presence_of_element_located(locator))
            return  element
        except Exception as e:
            print("定位失败：",e)


    # 发送信息
    def send_keys(self,target,text):
        self.locate_element(target).send_keys(text)

    # 点击元素
    def click_element(self,target):
        self.locate_element(target).click()

    # 跳转到iframe
    def iframe(self,target):
        a=self.locate_element(target)
        b=self.driver.switch_to.frame(a)
        return b
    # 返回上一层
    def iframe_up1(self):
        self.driver.switch_to.parent_frame()

    # 返回到最外层
    def iframe_up_max(self):
        self.driver.switch_to.default_content()

    # 根据下标进行选择下拉框
    def iframe_xiala(self,target,xiabiao):
        c=self.iframe(target)
        f = Select(c)
        f.select_by_index(xiabiao)

    # 根据文本进行选择下拉框
    def iframe_wenben(self,target,text):
        c=self.iframe(target)
        f = Select(c)
        f.select_by_visible_text(text)

    # 根据value进行选择下拉框
    def iframe_value(self,target,value):
        c=self.iframe(target)
        f = Select(c)
        f.select_by_value(value)

if __name__ == '__main__':
    #创建基础类对象
    bp = BasePage(getDriver("edge"))
    bp.open("http://127.0.0.1/ranzhi/www")
    # 定位元素
    bp.send_keys("id=account","admin")
    bp.send_keys("id=password","123456")
    bp.click_element("id=submit")
    time.sleep(10)


